<template>
  <div class="category-container">
    <!-- 顶部操作区域 -->
    <div class="operation-area">
      <!-- 查询表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input
            v-model="searchForm.categoryName"
            placeholder="请输入分类名称"
            clearable
            @keyup.enter="handleQuery"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" >查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 新增按钮 -->
      <div class="action-buttons">
        <el-button
          type="primary"
          @click="addDialogVisible = true"
        >新增分类</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-wrapper">
      <el-table
        :data="categoryList"
        border
        stripe
        highlight-current-row
        style="width: 100%"
        height="calc(100vh - 260px)"
      >
        <el-table-column prop="id" label="ID" width="100" align="center"></el-table-column>
        <el-table-column prop="categoryName" label="分类名称" min-width="150"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="150"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" min-width="150"></el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              plain
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              plain
              @click="handleDelete(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增分类对话框 -->
    <el-dialog
      title="新增分类"
      v-model="addDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="newCategory" :rules="rules" ref="addForm" label-position="right">
        <el-form-item label="分类名称" prop="categoryName" label-width="80px">
          <el-input
            v-model="newCategory.categoryName"
            placeholder="请输入分类名称"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog
      title="编辑分类"
      v-model="editDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="updateCategory" :rules="rules" ref="updateForm" label-position="right">
        <el-form-item label="分类名称" prop="categoryName" label-width="80px">
          <el-input
            v-model="updateCategory.categoryName"
            placeholder="请输入新分类名称"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import request from "@/api/request";
import {ElMessage, ElMessageBox} from "element-plus";

export default {
  name: "CategoryManage",
  data() {
    return {
      searchForm: {
        categoryName: ''
      },
      categoryList: [],
      newCategory: {
        categoryName: ''
      },
      updateCategory: {
        id: '',
        categoryName: ''
      },
      addDialogVisible: false,
      editDialogVisible: false,
      rules: {
        categoryName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async handleQuery() {
      try {
        const res = await request.get('/category/getCategory')
        this.categoryList = res.data
      } catch (error: any) {
        ElMessage.error('查询失败: ' + error.message)
      }
    },

    async handleAdd() {
      try {
        await (this.$refs.addForm as any).validate()
        const res = await request.post('/category/addCategory', this.newCategory)

        if(res.code === 200) {
          ElMessage.success('新增成功')
          this.newCategory.categoryName = ''
          this.addDialogVisible = false
          this.handleQuery()
        } else {
          ElMessage.error(res.message || '新增失败')
        }
      } catch (error: any) {
        if(!error.message) return
        ElMessage.error('新增失败: ' + error.message)
      }
    },

    handleEdit(row: any) {
      this.updateCategory = {
        id: row.id,
        categoryName: row.categoryName
      }
      this.editDialogVisible = true
    },

    async handleUpdate() {
      try {
        await (this.$refs.updateForm as any).validate()
        const res = await request.put('/category/update', this.updateCategory)

        if(res.code === 200) {
          ElMessage.success('更新成功')
          this.editDialogVisible = false
          this.handleQuery()
        } else {
          ElMessage.error(res.message || '更新失败')
        }
      } catch (error: any) {
        if(!error.message) return
        ElMessage.error('更新失败: ' + error.message)
      }
    },

    async handleDelete(id) {
      try {
        await ElMessageBox.confirm('确定要删除该分类吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const res = await request.delete(`/category/delete/${id}`)
        if(res.code === 200) {
          ElMessage.success('删除成功')
          this.handleQuery()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error: any) {
        if(error !== 'cancel') {
          ElMessage.error('删除失败: ' + error.message)
        }
      }
    }
  },
  created() {
    this.handleQuery()
  }
}
</script>

<style scoped >
.category-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  height: 95%;
  display: flex;
  flex-direction: column;
}

.operation-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .search-form {
    flex: 1;
    margin-right: 20px;

    ::v-deep .el-form-item {
      margin-bottom: 0;
    }
  }

  .action-buttons {
    white-space: nowrap;
  }
}

.table-wrapper {
  flex: 1;
  overflow: hidden;

  ::v-deep .el-table {
    height: 100%;

    .el-button {
      padding: 7px 10px;
    }
  }
}

::v-deep .el-dialog {
  border-radius: 8px;

  .el-form-item {
    margin-bottom: 22px;
  }

  .el-dialog__footer {
    text-align: center;
  }
}
</style>
